package com.wn.sddfp.gateway.config.black;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
@Slf4j
public class BlackIpUtils {

    private BitMapBloomFilter bloomFilter;

    @Autowired
    private BlackIpConfig blackIpConfig;



    /**
     * 更新布隆过滤器的方法
     */
    @PostConstruct
    @EventListener(RefreshScopeRefreshedEvent.class)
    public void updateBlackIpList() {
        BitMapBloomFilter newBloomFilter = new BitMapBloomFilter(100);
        List<String> blackIpList = blackIpConfig.getBlackIpList();
        blackIpList.forEach(newBloomFilter::add);
        bloomFilter = newBloomFilter;
    }

    public boolean isBlackIp(String ip) {
        log.info("访问的ip:"+ip);
        boolean contains = bloomFilter.contains(ip);
        return contains;
    }
}